import './FormAssembly.scss'
import dayjs from 'dayjs'
import { Http } from '../Api'
import { API_LIST } from '../Api/Api'
import { ICON } from '../Configure/Icon'
import {
    Form,
    Input,
    Button,
    InputNumber,
    Select,
    TreeSelect,
    Skeleton,
    DatePicker,
    Upload,
    message,
    Cascader,
    Alert,
} from 'antd'
import { useCallback, useEffect, useState } from 'react'
import { useBoolean, useEventEmitter, useRequest, useDebounceFn } from 'ahooks'
import { UploadFileType, UploadFileMapping } from '../Configure/CommonParameter'
import { UploadOutlined } from '@ant-design/icons'
import { ModalBox } from '../Modal/ModalBox'

const { TextArea } = Input

// 时间格式转换
const TimeFormatConversion = (data, { picker, showTime, showDate }, type) => {
    // TODO type 0 -> toString  1 -> toTime
    if (data) data = dayjs(`${data}`)
    else return ''

    let format = []
    switch (picker) {
        case 'year':
            format[0] = 'YYYY'
            break
        case 'month':
            if (showDate) format[0] = 'YYYY-MM-DD'
            else format[0] = 'YYYY-MM'
            break
        default:
            format[0] = 'YYYY-MM-DD'
            break
    }
    if (showTime) format[1] = 'HH:mm:ss'
    if (type === 0) return dayjs(data, format.join(' '))
    if (type === 1) return dayjs(data).format(format.join(' '))
}

export const FormAssembly = ({ Off, data, actionRef, AddTo, Adduuid, configure, Back, NoSubmit, reloadEvent }) => {
    const [form] = Form.useForm()
    const [PageData, setPageData] = useState()
    const [Middleware, setMiddleware] = useState()

    const [SubmitStatus, { setFalse: SubmitFalse }] = useBoolean(false)

    const [OptionsCall, setOptionsCall] = useState()
    const OptionsEvent = useEventEmitter()
    OptionsEvent.useSubscription(val => setOptionsCall(val))

    const RenderingForProcessing = useCallback(
        e => {
            const { columns, initialValues, CascaderInIt } = e
            if (!data && initialValues) form.setFieldsValue(initialValues)
            if (AddTo) form.setFieldsValue({ [AddTo.key]: AddTo.uuid })
            if (Adduuid) form.setFieldsValue(Adduuid)
            if (data) {
                const list = columns.filter(v => !v.hideInModify)
                let initial = JSON.parse(JSON.stringify(data))

                let Cascader = columns.filter(v => v.valueType === 'Cascader')
                if (Cascader.length > 0) {
                    Cascader.forEach(item => {
                        const data = item.valueList.map(key => initial[key])
                        initial[item.dataIndex] = data
                    })
                }
                // 判断时间数据
                let Date = columns.filter(v => v.valueType === 'Date')
                if (Date.length > 0)
                    Date.forEach(
                        item => (initial[item.dataIndex] = TimeFormatConversion(initial[item.dataIndex], item, 0)),
                    )
                if (CascaderInIt)
                    initial[CascaderInIt.dataIndex] = CascaderInIt.arr.reduce(
                        (result, item) => [...result, data[item]],
                        [],
                    )
                form.setFieldsValue(initial)
                setPageData(list)
            } else {
                setPageData(columns.filter(v => !v.hideInAdded))
            }
        },
        [AddTo, Adduuid, data, form],
    )

    const { runAsync } = useRequest(Http, {
        manual: true,
        throttleWait: 1500,
        onSuccess: e => callBack(e),
    })

    // !! 提交调试位置
    const Submit = e => {
        const { added, modify, columns } = Middleware
        // 数据处理过程
        let Cascader = columns.filter(v => v.valueType === 'Cascader')
        if (Cascader.length > 0) {
            Cascader.forEach(item => {
                const obj = item.valueList.reduce((acc, key, index) => {
                    acc[key] = e[item.dataIndex][index]
                    return acc
                }, {})
                e = { ...e, ...obj }
                delete e[item.dataIndex]
            })
        }
        let Date = columns.filter(v => v.valueType === 'Date')
        if (Date.length > 0)
            Date.forEach(item => (e[item.dataIndex] = TimeFormatConversion(e[item.dataIndex], item, 1)))
        if (Back) Back.emit(e)
        else {
            if (!!data) runAsync({ url: modify, data: { ...data, ...e }, path: [e.uuid] })
            else runAsync({ url: added, data: e, path: [e.uuid] })
        }
    }

    const callBack = e => {
        if (!!actionRef) actionRef.current.reload()
        else reloadEvent.emit(e)
        Off()
        SubmitFalse()
    }

    useEffect(() => {
        setMiddleware(configure)
        RenderingForProcessing(configure)
    }, [RenderingForProcessing, configure])

    return (
        <Form form={form} className="FormAssembly" name="validateOnly" layout="vertical" onFinish={Submit}>
            <div className="FormList">
                {PageData ? (
                    <FormItem form={form} PageData={PageData} OptionsEvent={OptionsEvent} />
                ) : (
                    <Skeleton active />
                )}
            </div>
            {!NoSubmit && (
                <div className="FormSub">
                    <Form.Item>
                        <Button className="FormSubmit" type="primary" htmlType="submit" loading={SubmitStatus}>
                            提交
                        </Button>
                    </Form.Item>
                </div>
            )}
            <ModalBox OptionsCall={OptionsCall} />
        </Form>
    )
}

export const FormItem = ({ form, PageData, OptionsEvent }) => {
    const [messageApi, contextHolder] = message.useMessage()

    // const { send: getOptions } = useRequest(({ url, params }) => Http({ url, params }), { immediate: false })
    const getOptions = () => {}

    return (
        <>
            {contextHolder}
            {PageData &&
                PageData.filter(Boolean).map((item, index) => {
                    const {
                        className,
                        valueType,
                        title,
                        dataIndex,
                        rules,
                        tooltip,
                        valueJudge,
                        JudgeValue,
                        valueEnum,
                        multiple,
                        fieldNames,
                        getUrl,
                        getFiles,
                        valueApi,
                        valueParams,
                    } = item

                    switch (valueType) {
                        // !!! 通用组件
                        //  隐藏
                        case 'hidden':
                            const HiddenForm = () => {
                                return (
                                    <Form.Item
                                        className="FormHidden"
                                        label={title}
                                        name={dataIndex}
                                        rules={[{ required: rules, message: `必须填写${title}!` }]}
                                    >
                                        <Input />
                                    </Form.Item>
                                )
                            }
                            return <HiddenForm key={`FormItem${index}`} />
                        // 输入框
                        case 'input':
                            const InputForm = () => {
                                const { pattern } = item
                                return (
                                    <Form.Item
                                        className={className || 'FormHalf'}
                                        label={title}
                                        name={dataIndex}
                                        tooltip={tooltip}
                                        rules={[{ required: rules, message: `必须填写${title}!` }]}
                                    >
                                        <Input
                                            style={{ width: '100%' }}
                                            placeholder={`请输入${title}`}
                                            pattern={pattern}
                                        />
                                    </Form.Item>
                                )
                            }
                            if (valueJudge)
                                return (
                                    <Form.Item
                                        key={`SearchForm-FormItem-${index}`}
                                        noStyle
                                        shouldUpdate={(prevValues, currentValues) =>
                                            prevValues[valueJudge] !== currentValues[valueJudge]
                                        }
                                    >
                                        {({ getFieldValue }) =>
                                            getFieldValue(valueJudge) === JudgeValue ? (
                                                <InputForm key={`FormItem${index}`} />
                                            ) : null
                                        }
                                    </Form.Item>
                                )
                            else return <InputForm key={`FormItem${index}`} />
                        //  数字框
                        case 'inputNumber':
                            const InputNumberForm = () => {
                                const { min } = item
                                return (
                                    <Form.Item
                                        className={className || 'FormHalf'}
                                        label={title}
                                        name={dataIndex}
                                        tooltip={tooltip}
                                        rules={[{ required: rules, message: `必须填写${title}!` }]}
                                    >
                                        <InputNumber
                                            placeholder={`请输入${title}`}
                                            style={{ width: `100%` }}
                                            min={min}
                                        />
                                    </Form.Item>
                                )
                            }
                            return <InputNumberForm key={`FormItem${index}`} />
                        //  多行文本
                        case 'textarea':
                            const TextAreaFrom = () => {
                                return (
                                    <Form.Item
                                        className="FormAll"
                                        label={title}
                                        name={dataIndex}
                                        tooltip={tooltip}
                                        rules={[{ required: rules, message: `必须填写${title}!` }]}
                                    >
                                        <TextArea placeholder={`请输入${title}`} autoSize={{ minRows: 4 }} />
                                    </Form.Item>
                                )
                            }
                            return <TextAreaFrom key={`FormItem${index}`} />
                        // 单选
                        case 'select':
                            const SelectForm = () => {
                                const [options, setOptions] = useState([])
                                useEffect(() => {
                                    if (
                                        form &&
                                        (form.getFieldValue(item.dataIndex) ||
                                            form.getFieldValue(item.dataIndex) === 0) &&
                                        typeof form.getFieldValue(item.dataIndex) === 'number'
                                    )
                                        form.setFieldsValue({
                                            [item.dataIndex]: form.getFieldValue(item.dataIndex).toString(),
                                        })
                                    let data
                                    if (valueEnum instanceof Array) data = valueEnum
                                    else
                                        data = Object.keys(valueEnum).map(key => ({
                                            label: valueEnum[key],
                                            value: key,
                                        }))
                                    const sortData = (x, y) => {
                                        if (x.label < y.label) return -1
                                        if (x.label > y.label) return 1
                                        return 0
                                    }
                                    setOptions(data.sort(sortData))
                                }, [])
                                return (
                                    <Form.Item
                                        className={className || 'FormHalf'}
                                        label={title}
                                        name={dataIndex}
                                        tooltip={tooltip}
                                        rules={[{ required: rules, message: `必须填写${title}!` }]}
                                    >
                                        <Select
                                            showSearch={true}
                                            placeholder={`请选择${title}`}
                                            mode={multiple ? 'multiple' : ''}
                                            fieldNames={fieldNames}
                                            filterOption={(input, option) =>
                                                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                            }
                                            options={options}
                                        />
                                    </Form.Item>
                                )
                            }

                            if (valueJudge)
                                return (
                                    <Form.Item
                                        key={`SearchForm-FormItem-${index}`}
                                        noStyle
                                        shouldUpdate={(prevValues, currentValues) =>
                                            prevValues[valueJudge] !== currentValues[valueJudge]
                                        }
                                    >
                                        {({ getFieldValue }) => {
                                            return getFieldValue(valueJudge) === JudgeValue ? (
                                                <SelectForm key={`FormItem${index}`} />
                                            ) : null
                                        }}
                                    </Form.Item>
                                )
                            else return <SelectForm key={`FormItem${index}`} />

                        case 'SelectApi':
                            const SelectApiTemp = () => {
                                const nameValue = Form.useWatch(valueJudge, form)
                                const [SelectApiOptions, setSelectApiOptions] = useState()

                                const { run } = useDebounceFn(
                                    () => {
                                        // if (initialValues[valueJudge] !== nameValue) form.setFieldsValue({ [dataIndex]: undefined })
                                        getOptions({
                                            url: valueApi,
                                            params: { OrganizationUuid: nameValue, DataType: valueParams },
                                        }).then(res => setSelectApiOptions(res[valueParams]))
                                    },
                                    { wait: 500 },
                                )

                                useEffect(() => {
                                    run()
                                }, [nameValue])
                                return (
                                    <Form.Item
                                        className="TwoFormItem"
                                        label={title}
                                        name={dataIndex}
                                        tooltip={tooltip}
                                        rules={[{ required: rules, message: '当前字段不得为空!' }]}
                                    >
                                        <Select
                                            placeholder={title}
                                            options={SelectApiOptions}
                                            fieldNames={fieldNames}
                                        />
                                    </Form.Item>
                                )
                            }
                            return <SelectApiTemp key={index} />

                        case 'selectArr':
                            const SelectArrForm = () => {
                                const [options, setOptions] = useState([])
                                const nameValue = Form.useWatch(getFiles, form)
                                const { runAsync } = useRequest(Http, {
                                    manual: true,
                                    onSuccess: res => setOptions(res.list),
                                })
                                useEffect(() => {
                                    if (nameValue) {
                                        console.log(nameValue)
                                        runAsync({ url: getUrl, data: { [getFiles]: nameValue } })
                                        // form.setFieldsValue({ [item.dataIndex]: null })
                                    }
                                }, [nameValue])
                                return (
                                    <Form.Item
                                        className={className || 'FormHalf'}
                                        label={title}
                                        name={dataIndex}
                                        tooltip={tooltip}
                                        rules={[{ required: rules, message: `必须填写${title}!` }]}
                                    >
                                        <Select
                                            allowClear={true}
                                            showSearch={true}
                                            fieldNames={{ value: 'uuid', label: 'fullName' }}
                                            placeholder={`请选择${title}`}
                                            filterOption={(input, option) =>
                                                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                            }
                                            options={options}
                                        />
                                    </Form.Item>
                                )
                            }
                            return <SelectArrForm key={`FormItem${index}`} />
                        //  树形下拉框
                        case 'treeSelect':
                            const TreeSelectForm = () => {
                                const { fieldProps } = item
                                return (
                                    <Form.Item
                                        className={className || 'FormHalf'}
                                        label={title}
                                        name={dataIndex}
                                        rules={[{ required: rules, message: `必须选择${title}!` }]}
                                    >
                                        <TreeSelect
                                            showSearch
                                            treeLine
                                            fieldNames={fieldProps.fieldNames}
                                            style={{ width: '100%' }}
                                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                            placeholder={`请选择${title}`}
                                            treeDefaultExpandAll
                                            treeData={fieldProps.options}
                                        />
                                    </Form.Item>
                                )
                            }
                            return <TreeSelectForm key={`FormItem${index}`} />

                        // 复选树形
                        case 'treeMultiple':
                            const TreeMultipleForm = () => {
                                const { fieldProps } = item

                                return (
                                    <Form.Item
                                        className={className || 'FormHalf'}
                                        label={title}
                                        name={dataIndex}
                                        rules={[{ required: rules, message: `必须选择${title}!` }]}
                                    >
                                        <TreeSelect
                                            showSearch
                                            treeLine
                                            multiple
                                            fieldNames={fieldProps.fieldNames}
                                            style={{ width: '100%' }}
                                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                            placeholder={`请选择${title}`}
                                            treeDefaultExpandAll
                                            treeData={fieldProps.options}
                                        />
                                    </Form.Item>
                                )
                            }
                            return <TreeMultipleForm key={`FormItem${index}`} />
                        // 联级选择
                        case 'selectMultiple':
                            const SelectMultipleFrom = () => {
                                const { valueEnum, fieldNames } = item
                                const [SelectMultipleOptions, setSelectMultipleOptions] = useState([])
                                return (
                                    <Form.Item
                                        noStyle
                                        shouldUpdate={(prevValues, currentValues) => {
                                            if (prevValues[valueJudge] !== currentValues[valueJudge]) {
                                                setSelectMultipleOptions(
                                                    valueEnum.find(v => v.uuid === currentValues[valueJudge]).children,
                                                )
                                                form.setFieldsValue({ [dataIndex]: [] })
                                                return true
                                            }
                                        }}
                                    >
                                        {({ getFieldValue }) => {
                                            return (
                                                getFieldValue(valueJudge) && (
                                                    <Form.Item
                                                        className={className || 'FormHalf'}
                                                        name={dataIndex}
                                                        label={title}
                                                        rules={[{ required: true }]}
                                                    >
                                                        <Select
                                                            mode="multiple"
                                                            placeholder={`请选择${title}`}
                                                            options={SelectMultipleOptions}
                                                            fieldNames={fieldNames}
                                                        />
                                                    </Form.Item>
                                                )
                                            )
                                        }}
                                    </Form.Item>
                                )
                            }
                            return <SelectMultipleFrom key={`FormItem${index}`} />

                        // 时间
                        case 'Date':
                            const { picker, showTime, disabledDate } = item
                            const DateForm = () => {
                                const disabledDateList = current => {
                                    return !disabledDate.includes(current.date())
                                }
                                return (
                                    <Form.Item
                                        className={className || 'FormHalf'}
                                        label={title}
                                        name={dataIndex}
                                        rules={[{ required: rules, message: `必须选择${title}!` }]}
                                    >
                                        <DatePicker
                                            style={{ width: '100%' }}
                                            picker={picker}
                                            showTime={showTime}
                                            disabledDate={disabledDate ? disabledDateList : false}
                                        />
                                    </Form.Item>
                                )
                            }

                            return <DateForm key={`FormItem${index}`} />
                        //  图标
                        case 'ICON':
                            const ICONForm = () => {
                                const Judge = Form.useWatch(valueJudge, form)
                                const [IconSelect, setIconSelect] = useState(form.getFieldValue(dataIndex))
                                const [MenuIconState, { setTrue: IconTrue, setFalse: IconFalse }] = useBoolean(false)
                                useEffect(() => form.setFieldsValue({ [dataIndex]: IconSelect }), [IconSelect])
                                useEffect(() => {
                                    if (Judge === JudgeValue) IconTrue()
                                    else IconFalse()
                                }, [IconFalse, IconTrue, Judge])

                                return (
                                    <>
                                        {MenuIconState && (
                                            <Form.Item
                                                className="FormAll"
                                                label={title}
                                                name={dataIndex}
                                                rules={[{ required: rules, message: `必须选择${title}!` }]}
                                            >
                                                <div className="SelectIcon">
                                                    {Object.keys(ICON).map((item, index) => (
                                                        <div
                                                            key={`SelectIcon${index}`}
                                                            className={IconSelect === item ? 'active' : ''}
                                                            onClick={() => setIconSelect(item)}
                                                        >
                                                            {ICON[item]}
                                                        </div>
                                                    ))}
                                                </div>
                                            </Form.Item>
                                        )}
                                    </>
                                )
                            }
                            return <ICONForm key={`FormItem${index}`} />
                        // 上传
                        case 'upload':
                            const { fileUrl, valueFile } = item

                            const UploadForm = () => {
                                const normFile = e => (Array.isArray(e) ? e : e?.fileList)
                                const [FileType, setFileType] = useState(0)
                                const [fileList, setFileList] = useState([])

                                useEffect(() => {
                                    const fileUrlText = form.getFieldValue(fileUrl)
                                    if (fileUrlText) setFileList([{ uid: '1', url: fileUrlText }])
                                }, [])

                                const beforeUpload = file => {
                                    const { size, name } = file
                                    const isLt1G = size / 1024 / 1024 / 1024 < 1
                                    let fileTypeIdex = false
                                    if (!isLt1G) messageApi.error('文件大小不得超过 1GB!')
                                    const fileType = name.split('.').at(-1).toLowerCase()
                                    UploadFileType.forEach((item, index) => {
                                        if (item.indexOf(fileType) !== -1) {
                                            fileTypeIdex = index
                                            setFileType(index)
                                        }
                                    })

                                    if (fileTypeIdex === false) {
                                        messageApi.error('暂不支持上传该文件类型,请及时联系管理员!')
                                        return false
                                    }

                                    if (valueFile.indexOf(fileTypeIdex) === -1) {
                                        let tipsTxt = ''
                                        valueFile.forEach(item => (tipsTxt += ` ${UploadFileMapping[item]}`))
                                        messageApi.error(`请上传 ${tipsTxt}`)
                                        return false
                                    }
                                    return isLt1G
                                }
                                const props = () => {
                                    return {
                                        name: 'file',
                                        action: API_LIST()[`posAttachment`],
                                        headers: { Authorization: `${sessionStorage.getItem('TOKEN')}` },
                                        maxCount: 1,
                                        listType: 'picture',
                                        fileList,
                                        onChange(info) {
                                            const { file, fileList } = info
                                            const { response, name } = file
                                            setFileList(fileList)
                                            if (file.status === 'done') {
                                                const { uuid, fileUrl } = response
                                                form.setFieldsValue({ [dataIndex]: uuid, fileUrl: fileUrl })
                                                messageApi.success(`${name} 上传成功`)
                                            } else if (file.status === 'error') messageApi.error(`${name} 上传失败.`)
                                        },
                                        onPreview(info) {
                                            const { size, response, url } = info
                                            const AttUrl = size ? response.fileUrl : url
                                            OptionsEvent.emit({
                                                type: 'Annex',
                                                data: {
                                                    width: '80vw',
                                                    title: '查看附件',
                                                    url: AttUrl,
                                                },
                                            })
                                        },
                                        onRemove() {
                                            form.setFieldsValue({ [dataIndex]: null })
                                        },
                                    }
                                }
                                return (
                                    <Form.Item
                                        className="FormAll"
                                        label={title}
                                        name={dataIndex}
                                        rules={[{ required: rules, message: `必须选择${title}!` }]}
                                        getValueFromEvent={normFile}
                                    >
                                        <Alert message="严守保密红线，杜绝云端涉密。" type="error" showIcon />
                                        <div style={{ height: 8 }} />
                                        <Upload beforeUpload={beforeUpload} data={{ FileType }} {...props()}>
                                            <Button icon={<UploadOutlined />}>点击上传</Button>
                                        </Upload>
                                    </Form.Item>
                                )
                            }
                            return <UploadForm key={`FormItem${index}`} />
                        // !!! 独立添加项
                        // 梁场管理 - 梁生产管理 - 梁号选择 - 联级
                        case 'beamCascader':
                            const BeamCascader = () => {
                                const { runAsync } = useRequest(Http, { manual: true })
                                const [options, setOptions] = useState()
                                const [one] = useState('getBeam')
                                const [two] = useState([
                                    { label: '无', value: '0', isLeaf: false },
                                    { label: '左幅', value: '1', isLeaf: false },
                                    { label: '右幅', value: '2', isLeaf: false },
                                ])
                                const [thr] = useState('getBeamGetBeamNoListByBridgeNameAndPart')

                                useEffect(() => {
                                    runAsync({ url: one }).then(res => {
                                        setOptions(
                                            res.list.map(item => ({
                                                label: item.bridgeName,
                                                value: item.bridgeName,
                                                isLeaf: false,
                                            })),
                                        )
                                    })
                                }, [runAsync, one])

                                const loadData = e => {
                                    const { length } = e
                                    const targetOption = e[length - 1]
                                    if (length === 1) {
                                        targetOption.children = two
                                        setOptions([...options])
                                    }
                                    if (length === 2) {
                                        runAsync({ url: thr, data: { BridgeName: e[0].value, Part: e[1].value } }).then(
                                            res => {
                                                targetOption.loading = false
                                                targetOption.children = res.list.map(item => ({
                                                    label: item.beamNo,
                                                    value: item.uuid,
                                                }))
                                                setOptions([...options])
                                            },
                                        )
                                    }
                                }

                                const change = e => {
                                    if (e.length === 3) form.setFieldsValue({ beamUuid: e.at(-1) })
                                    else form.setFieldsValue({ beamUuid: null })
                                }

                                return (
                                    <Form.Item
                                        className={className || 'FormHalf'}
                                        label={title}
                                        name={dataIndex}
                                        tooltip={tooltip}
                                        rules={[{ required: rules, message: `必须选择${title}!` }]}
                                    >
                                        <Cascader
                                            placeholder={`请选择${title}`}
                                            changeOnSelect
                                            loadData={loadData}
                                            options={options}
                                            onChange={change}
                                        />
                                    </Form.Item>
                                )
                            }
                            return <BeamCascader key={`FormItem${index}`} />
                        // 自动补全
                        case 'automatically':
                            const AutomaticForm = () => {
                                const { addonAfter, addonBefore, addonField, addonType, initialValues } = item
                                const addonFieldWatch = Form.useWatch(addonField, form)

                                useEffect(() => {
                                    if (addonFieldWatch) {
                                        if (addonType === 'yearMonth') {
                                            const Y = addonFieldWatch.year()
                                            const M = addonFieldWatch.month() + 1
                                            const text = `${addonAfter || ''}${initialValues}${Y}年${M}月${
                                                addonBefore || ''
                                            }`
                                            form.setFieldValue([dataIndex], text)
                                        }
                                    }
                                }, [addonAfter, addonBefore, addonFieldWatch, addonType, initialValues])

                                return (
                                    <Form.Item
                                        className="FormHidden"
                                        label={title}
                                        name={dataIndex}
                                        rules={[{ required: rules, message: `必须填写${title}!` }]}
                                    >
                                        <Input
                                            disabled={true}
                                            style={{ width: '100%' }}
                                            placeholder={`请输入${title}`}
                                        />
                                    </Form.Item>
                                )
                            }
                            return <AutomaticForm key={`FormItem${index}`} />
                        // 备注信息
                        case 'help':
                            const HelpForm = () => {
                                const { runAsync: getDate } = useRequest(Http, { manual: true })
                                const [text, setText] = useState()
                                const yearMonth = Form.useWatch('yearMonth', form)
                                const organizationUuid = Form.useWatch('organizationUuid', form)

                                useEffect(() => {
                                    const { helpUrl, helpText } = item
                                    if (dataIndex === 'bada' && yearMonth && organizationUuid) {
                                        const year = yearMonth.year()
                                        getDate({ url: helpUrl, data: { year, organizationUuid } }).then(res => {
                                            const { totalAmount, yearAmount } = res
                                            setText(
                                                `${year}年累计${helpText}：${yearAmount}万元、项目累计${helpText}：${totalAmount}万元`,
                                            )
                                        })
                                    }
                                }, [organizationUuid, yearMonth, getDate])
                                return <div className="FormHelp">{text}</div>
                            }
                            return <HelpForm key={`FormItem${index}`} />

                        case 'Cascader':
                            const CascaderForm = () => {
                                return (
                                    <Form.Item
                                        className="FormHalf"
                                        label={title}
                                        name={dataIndex}
                                        rules={[{ required: rules, message: `必须填写${title}!` }]}
                                    >
                                        <Cascader options={valueEnum} placeholder={`请选择${title}`} />
                                    </Form.Item>
                                )
                            }
                            return <CascaderForm key={index} />
                        default:
                            const UnknownForm = () => {
                                return (
                                    <Form.Item
                                        className="FormHalf"
                                        label={title}
                                        name={dataIndex}
                                        tooltip="未知 类型组件,请与开发者或管理员确认"
                                        rules={[{ required: rules, message: `必须填写${title}!` }]}
                                    >
                                        <div>未知组件</div>
                                    </Form.Item>
                                )
                            }
                            return <UnknownForm key={`FormItem${index}`} />
                    }
                })}
        </>
    )
}

export const IndependenceUpload = ({ type, valueFile, UploadEvent }) => {
    const [FileType, setFileType] = useState(0)
    const [Loading, setLoading] = useState(false)
    const [messageApi, contextHolder] = message.useMessage()

    const beforeUpload = file => {
        const { size, name } = file
        const isLt1G = size / 1024 / 1024 / 1024 < 1
        let fileTypeIdex = false
        if (!isLt1G) messageApi.error('文件大小不得超过 1GB!')
        const fileType = name.split('.').at(-1).toLowerCase()
        UploadFileType.forEach((item, index) => {
            if (item.indexOf(fileType) !== -1) {
                fileTypeIdex = index
                setFileType(index)
            }
        })

        if (fileTypeIdex === false) {
            messageApi.error('暂不支持上传该文件类型,请及时联系管理员!')
            return false
        }

        if (valueFile.indexOf(fileTypeIdex) === -1) {
            let tipsTxt = ''
            valueFile.forEach(item => (tipsTxt += ` ${UploadFileMapping[item]}`))
            messageApi.error(`请上传 ${tipsTxt}`)
            return false
        }
        return isLt1G
    }

    const [number, setNumber] = useState(0)
    const [fileList, setFileList] = useState(0)
    const [uuidList, setUuidList] = useState([])

    const props = {
        name: 'file',
        action: API_LIST()[`posAttachment`],
        headers: { Authorization: `${sessionStorage.getItem('TOKEN')}` },
        showUploadList: false,
        multiple: true,
        onChange(info) {
            setLoading(true)
            const { file, fileList } = info
            const { status, response, name } = file
            setNumber(fileList.length)
            if (status === 'done') {
                const { uuid } = response
                messageApi.success(`${name} 上传成功`)
                setUuidList(e => [...e, uuid])
                setFileList(e => e + 1)
            } else if (status === 'error') {
                messageApi.error(`${name} 上传失败.`)
                setFileList(e => e + 1)
            }
        },
    }

    useEffect(() => {
        if (number === fileList) {
            setLoading(false)
            UploadEvent.emit({ type, uuidList })
        }
    }, [UploadEvent, fileList, number, type, uuidList])

    return (
        <Upload beforeUpload={beforeUpload} data={{ FileType: FileType }} {...props}>
            {contextHolder}
            <Button type="primary" loading={Loading} icon={<UploadOutlined />}>
                新增
            </Button>
        </Upload>
    )
}
